package com.gp.gback.system.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by kongryan on 16/9/5.
 */
public class ListAttrTypeHandler extends BaseTypeHandler<List<Object>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Object> objects, JdbcType jdbcType) throws SQLException {
        if(objects != null){
            preparedStatement.setString(i, ""+JSON.toJSONString(objects));
        }
    }

    @Override
    public List<Object> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        if(resultSet.getString(s) == null){
            return null;
        }
        return JSONArray.parseArray(resultSet.getString(s), Object.class);
//        return Arrays.asList(resultSet.getString(s).split(","));
    }

    @Override
    public List<Object> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        if(resultSet.getString(i) == null){
            return null;
        }
        return JSONArray.parseArray(resultSet.getString(i), Object.class);
//        return Arrays.asList(resultSet.getString(i).split(","));
    }

    @Override
    public List<Object> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        if(callableStatement.getString(i) == null){
            return null;
        }
        return JSONArray.parseArray(callableStatement.getString(i), Object.class);
//        return Arrays.asList(callableStatement.getString(i).split(","));
    }
}
